package com.github.shiqiyue.myadmin.util.web;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

/***
 * 文件上传
 *
 * @author wwy
 *
 */
public class FileUpload {

    private static final DateFormat SDF = new SimpleDateFormat("/yyyy/MM/dd/");

    private static final Random RANDOM = new Random();

    private static final Logger LOG = LoggerFactory.getLogger(FileUpload.class);


    public static String getDate() {
        return SDF.format(new Date());
    }

    /**
     * 上传文件
     *
     * @param file     //文件对象
     * @param filePath //上传路径
     * @param fileName //文件名
     * @return 文件名
     */
    public static String fileUp(MultipartFile file, String filePath, String fileName) {
        // 扩展名格式

        String extName = "";
        String date = getDate();
        String randomInt = RANDOM.nextInt(10) + "/";
        try {
            if (file.getOriginalFilename().lastIndexOf(".") >= 0) {
                extName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            }
            copyFile(file.getInputStream(), filePath + date + randomInt, fileName + extName).replaceAll("-", "");
        } catch (IOException e) {
            LOG.error("上传文件失败", e);
        }
        return date + randomInt + fileName + extName;
    }

    /**
     * 写文件到当前目录的upload目录中
     *
     * @param in
     * @param fileName
     * @throws IOException
     */
    private static String copyFile(InputStream in, String dir, String realName) throws IOException {
        File file = mkdirsmy(dir, realName);
        FileUtils.copyInputStreamToFile(in, file);
        return realName;
    }

    /**
     * 判断路径是否存在，否：创建此路径
     *
     * @param dir      文件路径
     * @param realName 文件名
     * @throws IOException
     */
    public static File mkdirsmy(String dir, String realName) throws IOException {
        File file = new File(dir, realName);
        if (!file.exists()) {
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            file.createNewFile();
        }
        return file;
    }

}
